﻿using Furion;
using Microsoft.Extensions.Configuration;
using System.Globalization;
using System.Reflection;
using System.Resources;
using System.Threading;
using YFurion.Extensions;
using YFurion.Session;

namespace YFurion.Localization
{
    public class LocalizationManager : ILocalizationManager
    {
        private readonly IYSession _ySession;

        public LocalizationManager(IYSession ySession)
        {
            _ySession = ySession;
        }

        public string Culture
        {
            get
            {
                return _ySession.Culture.IsNullOrWhiteSpace() ? Thread.CurrentThread.CurrentCulture.Name : _ySession.Culture;
            }
            set
            {
                _ySession.Culture = value;
            }
        }

        public string this[string name]
        {
            get
            {
                return GetEntryString(name);
            }
        }

        /// <summary>
        /// Get entry string by name
        /// </summary>
        /// <param name="name">名称</param>
        /// <returns></returns>
        public string GetEntryString(string name)
        {
            string suffix = App.Configuration.Get<string>("LocalizationSettings:Suffix");
            return GetString(name, Assembly.GetEntryAssembly().FullName, suffix.IsNullOrWhiteSpace() ? "Resources.Lang" : suffix);
        }

        /// <summary>
        /// Get string by name
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="assemblyName">程序集名称</param>
        /// <returns>language string</returns>
        public string GetString(string name, string assemblyName)
        {
            return GetString(name, assemblyName, LocalizationConst.LocalizationManagerNameSuffix);
        }

        /// <summary>
        /// Get string by name
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="assemblyName">程序集名称</param>
        /// <param name="suffix">后缀</param>
        /// <returns>language string</returns>
        public string GetString(string name, string assemblyName, string suffix)
        {
            string strCurLanguage;
            try
            {
                Assembly assembly = Assembly.Load(assemblyName);
                ResourceManager rm = new ResourceManager($"{assembly.GetName().Name}.{suffix}", assembly);
                CultureInfo ci = new CultureInfo(Culture);
                strCurLanguage = rm.GetString(name, ci);
            }
            catch
            {
                strCurLanguage = name;
            }

            return strCurLanguage;
        }
    }
}
